﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.DiaoDongService;
using CommunitySystem.PageView.EmpBasicManager;

namespace CommunitySystem
{
    public partial class DiaoDongWindow_DiaoChuBenQu : ChildWindow
    {
        private DiaoDongService.DiaoDongModel model = new DiaoDongService.DiaoDongModel();
        private DiaoDongService.DiaoDongServiceClient Client = new DiaoDongService.DiaoDongServiceClient();
        private EmpbasicService.EmpBasicServiceClient empclient = new EmpbasicService.EmpBasicServiceClient();
        public int ID;
        public int OrgID;
        public bool IsNew = false;
        public string SFCK = "";
        public DiaoDongWindow_DiaoChuBenQu(int orgID, int iD, bool isnew, string shifouchakan, string type)
        {
            InitializeComponent();
            
            ID = iD;
            OrgID = orgID;
            IsNew = isnew;
            SFCK = shifouchakan;
            if (IsNew)
            {
                this.Title = "新增调动信息";
                model = new DiaoDongModel();
                model.Type = "调出本区";
                this.DataContext = model;
            }
            else
            {
                this.Title = "编辑调动信息";
                Client.GetDiaoDongAsync("", ID,"","","");
            }
            if (shifouchakan == "查看")
            {
                name.IsEnabled =
                    cardno.IsEnabled =
                    gender.IsEnabled =
                    birthday.IsEnabled =  false;
            }
            else
            {
                name.IsEnabled =
                    cardno.IsEnabled =
                    gender.IsEnabled =
                    birthday.IsEnabled =    true;
            }
            empclient.GetEmp_BasicInfoModelByCardNoCompleted +=
                new EventHandler<EmpbasicService.GetEmp_BasicInfoModelByCardNoCompletedEventArgs>(empclient_GetEmp_BasicInfoModelByCardNoCompleted);
            Client.GetDiaoDongCompleted += new EventHandler<GetDiaoDongCompletedEventArgs>(Client_GetDiaoDongCompleted);
            Client.AddDiaoDongCompleted += new EventHandler<AddDiaoDongCompletedEventArgs>(Client_AddDiaoDongCompleted);
            Client.UpdateDiaoDongCompleted += new EventHandler<UpdateDiaoDongCompletedEventArgs>(Client_UpdateDiaoDongCompleted);

        }

        void Client_GetDiaoDongCompleted(object sender, GetDiaoDongCompletedEventArgs e)
        {
            if (e.Result != null)
                model = e.Result[0];
            this.DataContext = model;
        }
        void empclient_GetEmp_BasicInfoModelByCardNoCompleted(object sender, EmpbasicService.GetEmp_BasicInfoModelByCardNoCompletedEventArgs e)
        {
            if (e.Result != null && e.Result.Count > 0)
            {
                model.EmpbasicID = e.Result[0].EmpbasicID;
                model.Name = e.Result[0].Name;
                model.Gender = e.Result[0].Gender;
                model.Birthday = e.Result[0].Birthday;
                model.OrgName = e.Result[0].OrgName;
                model.PositionName = e.Result[0].PositionName;
                model.DutyName = e.Result[0].DutyName;
                this.DataContext = model;
                OKButton.IsEnabled = true;
            }
            else
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("输入有误，请检查后重新输入！");
                OKButton.IsEnabled = false;
            }
        }
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            //if (string.IsNullOrEmpty(name.Text))
            //{
            //    SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员姓名！");
            //    return;
            //}
            if (Valid())
            {
                model.Status = "未审核";
                if (IsNew)
                {
                    model.RZQMSJ = DateTime.Today;
                    model.NewOrgID = OrgID;
                    Client.AddDiaoDongAsync(model);
                }
                else Client.UpdateDiaoDongAsync(model);
            }
        }
        void Client_UpdateDiaoDongCompleted(object sender, UpdateDiaoDongCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("编辑成功！");
                this.DialogResult = true;
            }
        }

        void Client_AddDiaoDongCompleted(object sender, AddDiaoDongCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("新增成功！");

                this.DialogResult = true;
            }
        }
        #region 身份证验证
        private void textBoxCode2_LostFocus(object sender, EventArgs e)
        {
            SetStatus(cardno.Text);
        }
        public void SetStatus(string idcard)
        {
            if (ValiIdCard(idcard))
            {
                model.Gender = Checks.IsMan(idcard) ? "男" : "女";
                gender.Field = "Gender";
                model.Birthday = Convert.ToDateTime(Checks.GetBirthDay(idcard).ToString());
                if (model.ID <= 0 || (!string.IsNullOrEmpty(model.CardNo) && model.CardNo != idcard))
                    empclient.GetEmp_BasicInfoModelByCardNoAsync(idcard, OrgID);
            }
        }
        public static bool IsStringMissing(string value)
        {
            return
                String.IsNullOrEmpty(value) ||
                value.Trim() == String.Empty;
        }
        public static bool ValiIdCard(string idcard)
        {
            if (IsStringMissing(idcard)) return false;
            if (idcard == null || (idcard.Length != 15 && idcard.Length != 18))
            {
                return false;
            }

            if (idcard.Length == 18)
            {
                System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{17}(\d|x|X)$");
                System.Text.RegularExpressions.Match mc = rg.Match(idcard);
                if (!mc.Success)
                {
                    return false;
                }

                if (int.Parse(idcard.Substring(6, 4)) < 1850 || int.Parse(idcard.Substring(6, 4)) > DateTime.Now.Year + 1)
                {
                    return false; // 不允许 1850年以前的日期，以及不允许当前年＋2以后的日期

                }

                try
                {
                    DateTime.Parse(idcard.Substring(6, 4) + "-" + idcard.Substring(10, 2) + "-" + idcard.Substring(12, 2));
                }
                catch
                {
                    return false;
                }

                string idcard15 = idcard.Substring(0, 6) + idcard.Substring(8, 9);

                //if (GetLongIDCardNumber(idcard15) != idcard)
                //{
                //    return false;
                //}

            }
            else if (idcard.Length == 15)
            {
                System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{15}");
                System.Text.RegularExpressions.Match mc = rg.Match(idcard);
                if (!mc.Success)
                {
                    return false;
                }

                try
                {
                    DateTime.Parse("19" + idcard.Substring(6, 2) + "-" + idcard.Substring(8, 2) + "-" + idcard.Substring(10, 2));
                }
                catch
                {
                    return false;
                }
            }

            string[] aCity = new string[]{null,null,null,null,null,null,null,null,null,null,null,
											 "北京","天津","河北","山西","内蒙古",null,null,null,null,null,
											 "辽宁","吉林","黑龙江",null,null,null,null,null,null,null,
											 "上海","江苏","浙江","安微","福建","江西","山东",null,null,null,
											 "河南","湖北","湖南","广东","广西","海南",null,null,null,
											 "重庆","四川","贵州","云南","西藏",null,null,null,null,null,null,
											 "陕西","甘肃","青海","宁夏","新疆",null,null,null,null,null,
											 "台湾",null,null,null,null,null,null,null,null,null,
											 "香港","澳门",null,null,null,null,null,null,null,null,"国外"};
            if (aCity[int.Parse(idcard.Substring(0, 2))] == null)
            {
                return false;
            }

            return true;
        }
        public static string GetLongIDCardNumber(string idcard)
        {
            //		计算方法
            //		(1)十七位数字本体码加权求和公式
            //			   S = Ai * Wi, i = 2, ... , 18
            //		Y = mod(S, 11)
            //		i: 表示号码字符从右至左包括校验码字符在内的位置序号
            //			   Ai:表示第i位置上的身份证号码字符值

            //					  Wi:表示第i位置上的加权因子
            //							 i: 18 17 16 15 14 13 12 11 10 9 8 7  6 5 4 3 2 1
            //		Wi: 7  9 10  5  8  4  2  1  6 3 7 9 10 5 8 4 2 1
            //		(2)校验码字符值的计算
            //			   Y:      0 1 2 3 4 5 6 7 8 9 10
            //		校验码: 1 0 X 9 8 7 6 5 4 3  2

            if (!ValiIdCard(idcard))
            {
                return null;
            }

            if (idcard.Length == 18)
            {
                return idcard;
            }

            idcard = idcard.Substring(0, 6) + "19" + idcard.Substring(6, 9);

            int[] Wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
            string[] CK = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };

            int sig = 0;
            int i;

            for (i = 0; i < 17; i++)
            {
                sig += Wi[i] * int.Parse(idcard.Substring(i, 1));
            }
            int y = sig % 11;

            for (i = 0; i < 11; i++)
            {
                if (y == i)
                {
                    idcard += CK[i];
                }
            }

            return idcard;
        }
        #endregion

        public bool Valid()
        {
            if (string.IsNullOrEmpty(model.Name))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员姓名！");
                return false;
            }
            if (string.IsNullOrEmpty(model.CardNo))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员证件号码！");
                return false;
            }
            if (string.IsNullOrEmpty(model.Gender))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员性别！");
                return false;
            }
            if (string.IsNullOrEmpty(model.Birthday.ToString()))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员出生日期！");
                return false;
            }
            if (string.IsNullOrEmpty(model.NewOrgName))
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入人员现单位！");
                return false;
            }
            
            return true;
        }
    }
}
